package com.whz.gateway.configure;

import com.whz.gateway.common.constants.GatewayConstant;
import com.whz.gateway.handler.captcha.img.ImageCodeCheckHandler;
import com.whz.gateway.handler.captcha.img.ImageCodeGenerateHandler;
import com.whz.gateway.handler.captcha.sms.SmsCheckHandler;
import com.whz.gateway.handler.captcha.sms.SmsSendHandler;
import com.whz.gateway.limit.sentinel.GatewayFallbackHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;
import org.springframework.web.reactive.function.server.ServerResponse;

import javax.annotation.Resource;

/**
 * 直接在gateway处理的请求,不upstream到微服务
 *
 * @author whz
 */
@Slf4j
@Configuration
public class CustomRouterFunctionConfigure {

    @Resource
    private ImageCodeGenerateHandler imageCodeWebHandler;

    @Resource
    private ImageCodeCheckHandler imageCodeCheckHandler;

    @Resource
    private GatewayFallbackHandler fallbackHandler;

    @Resource
    private SmsCheckHandler smsCheckHandler;

    @Resource
    private SmsSendHandler smsSendHandler;

    @Bean
    public RouterFunction<ServerResponse> routerFunction() {
        return RouterFunctions.route(
                                      // 熔断服务降级处理
                                      RequestPredicates.path(GatewayConstant.FALL_BACK_PATH), fallbackHandler)
                              // 图片验证码生成处理
                              .andRoute(RequestPredicates.POST(GatewayConstant.IMAGE_CODE_PATH), imageCodeWebHandler)
                              // 验证码校验
                              .andRoute(RequestPredicates.POST(GatewayConstant.IMAGE_CODE_CHECK), imageCodeCheckHandler)
                              // 短信验证码
                              .andRoute(RequestPredicates.POST(GatewayConstant.SMS_SEND_PATH), smsSendHandler)
                              // 验证短信验证码
                              .andRoute(RequestPredicates.POST(GatewayConstant.SMS_CHECK_PATH), smsCheckHandler);
    }
}